package httpx

import (
	"encoding/csv"
	"io"
)

func ProcessTSV(read func(reader *csv.Reader) error, skip ...int) ProcessFunc {
	return processCSV(read, '\t', skip)
}

func ProcessCSV(read func(reader *csv.Reader) error, skip ...int) ProcessFunc {
	return processCSV(read, ',', skip)
}

func processCSV(read func(reader *csv.Reader) error, comma rune, skip []int) ProcessFunc {
	return ProcessProgress(func(r io.Reader) error {
		cr := csv.NewReader(r)
		{
			cr.TrimLeadingSpace = true
			cr.ReuseRecord = true
			cr.Comma = comma
		}

		if len(skip) > 0 && skip[0] > 0 {
			for i := 0; i < skip[0]; i++ {
				if _, err := cr.Read(); err != nil {
					return err
				}
			}
		}

		return read(cr)
	})
}
